package com.fwzhang.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

public class PdfToImage {

    public static void main(String[] args)  {
//        try {
//            PdfToImage.icepdfTest();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        PdfToImage.pdfBox();
    }

    public static void icepdfTest() throws InterruptedException, IOException, PDFException, PDFSecurityException {
//        String filePath = "C:\\Users\\Magfin\\Desktop\\工作\\需求整理\\流水Pdf转excel\\可用\\IQP202004260000329989_1月民泰.pdf";
        String filePath = "C:\\Users\\Magfin\\Desktop\\赵明天流水.pdf";
        Document document = new Document();
        document.setFile(filePath);
        float scale = 5f;//缩放比例
        float rotation = 0f;//旋转角度
        for (int i = 0; i < document.getNumberOfPages(); i++) {

            BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
//            RenderedImage rendImage = image;
            try {
                File file = new File("C:\\Users\\Magfin\\Desktop\\iecPDF_nong_" + i + ".jpg");
                ImageIO.write(image, "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
    }

    public static void pdfBox() {
        File source = new File("C:\\Users\\Magfin\\Desktop\\工作\\需求整理\\流水Pdf转excel\\可用\\IQP202005210000344409_mx20200518135628490226888.pdf");
//        File source = new File("C:\\Users\\Magfin\\Desktop\\赵明天流水.pdf");
        try {
             PDDocument doc = PDDocument.load(source);
             PDFRenderer renderer = new PDFRenderer(doc);
             int pageCount = doc.getNumberOfPages();
             for (int i = 0; i < pageCount; i++) {
//                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                BufferedImage image = renderer.renderImage(i, 5f);
                File file = new File("C:\\Users\\Magfin\\Desktop\\iecPDF_nong_" + i + ".jpg");
                ImageIO.write(image, "PNG", file);
              }
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}
